package com.zhdl.network.common_client;

import com.project.command.faq.state.LinkStateService;
import com.project.network.client.SerialSocketClient;
import com.project.network.conf.LinkClientSocketBuild;
import com.project.network.entity.PortSocket;
import com.zhdl.modules.demo.hardware_connect.ConnectManager;
import com.zhdl.network.common_client.dto.CommonClientPacket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.tio.client.intf.TioClientHandler;

import javax.annotation.Resource;

import static com.zhdl.network.common_client.CommonTcpClientAnalysis.COMMON_TCP_ANALYSIS;

@Slf4j
@Component
public class CommonTcpClientSocketBuild extends LinkClientSocketBuild {

    @Resource
    private LinkStateService linkStateService;
    @Resource
    ConnectManager connectManager;

    protected SerialSocketClient buildClient(PortSocket properties) {
        String port = properties.getClientPort();
        String clientIp = properties.getClientIp();
        String protocols = properties.getProtocols();
        String serverIp = properties.getServerIp();
        String serverPort = properties.getServerPort();
        Integer timeouts = properties.getTimeouts();

        TioClientHandler handler = null;

        //此处判断 handler 是ModBusTcp 还是 其他自定义协议
        if (properties.getProtocols().equals("modbus_tcp")) {
            handler = new CommonTcpClientHandler(serverIp, serverPort, protocols, message);
        } else {
            handler = new CommonOtherClientHandler(serverIp, serverPort, protocols, message);
        }

        //获取IP + Port
        String server = serverIp + ":" + serverPort;

        //创建Socket服务
        CommonTcpClientListener listener = new CommonTcpClientListener();
        listener.setStateService(linkStateService);
        listener.setServer(server);
        CommonClientPacket packet = new CommonClientPacket();
        Integer clientPort = Integer.parseInt(port);

        SerialSocketClient socket = new SerialSocketClient(handler, listener, packet, serverIp, serverPort, port, clientIp, clientPort, timeouts);
        try {
            socket.openSocket();
        } catch (Exception e) {
            throw exceptionBuild.newException("9999", e);
        }
        return socket;
    }

    @Override
    protected SerialSocketClient buildSocketClient(PortSocket properties) {
        // mod-bus
        if (COMMON_TCP_ANALYSIS.equals(properties.getProtocols())) {
            return buildClient(properties);
        } //预留 modbus_tcp 但是暂时不做处理
        else if ("modbus_tcp".equals(properties.getProtocols())) {
            return buildClient(properties);
        }
        return null;
    }
}
